import 'package:graphql/client.dart';
import 'package:incidentmanager/common/config/constant.dart';
import 'package:incidentmanager/common/data/api/queries/get_post.dart';
import 'package:incidentmanager/models/post.dart';

class GetPostRequestFailure implements Exception {}

class ApiClient {
  const ApiClient({GraphQLClient graphQLClient})
      : assert(graphQLClient != null),
        _graphQLClient = graphQLClient;

  factory ApiClient.create() {
    final httpLink = HttpLink(uri: API_URL);
    final link = Link.from([httpLink]);
    return ApiClient(
      graphQLClient: GraphQLClient(cache: InMemoryCache(), link: link),
    );
  }

  final GraphQLClient _graphQLClient;

  Future<List<Post>> getJobs() async {
    final result = await _graphQLClient.query(
      QueryOptions(documentNode: gql(getPost)),
    );
    if (result.hasException) {
      throw GetPostRequestFailure();
    }
    final data = result.data['jobs'] as List;
    return data.map((e) => Post.fromJson(e)).toList();
  }
}
